package cn.golxen.blog.redis;

import cn.golxen.blog.commons.rabbitVo.UpdateMySqlViewsVo;
import cn.golxen.blog.rabbitMQ.producer.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Slf4j
@Component
public class RedisExpiredKeyListener extends KeyExpirationEventMessageListener {

    @Autowired
    RedisTemplate<String,String> redisTemplate;
    @Autowired
    Producer producer;

    public RedisExpiredKeyListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        log.info("监听到过期key："+message.toString());
//        log.info(new String(pattern));
        if (message.toString().contains("viewsId:")){
            String key= message.toString().substring(8);
            Integer value= Integer.valueOf(Objects.requireNonNull(redisTemplate.opsForValue().get("viewsId_2:" + key)));
            log.info(String.valueOf(value));
            producer.essayProducer(new UpdateMySqlViewsVo(key,value));
            redisTemplate.delete("viewsId_2:" + key);
        }
    }
}
